package io.bluerain.android.sdk.update.core.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import io.bluerain.android.sdk.update.core.Constants;
import io.bluerain.android.sdk.update.core.entities.Log;
import io.bluerain.android.sdk.update.core.entities.Result;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by foredawn on 15-9-20.
 * 检测升级服务
 */
public class UpdateService extends Service {

    private Boolean lastVersion;
    private Log updateLog;

    public class UpBinder extends Binder {

        public Boolean isLastVersion() {
            return lastVersion;
        }

        public Log getUpdateLog() {
            return updateLog;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new UpBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //检测更新服务
        new Thread(new Runnable() {
            @Override
            public void run() {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(Constants.SERVER_ADDRESS)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();

                IUpdateService service = retrofit.create(IUpdateService.class);
                Map<String, String> options = new HashMap<>();
                options.put(Constants.PARAM_VERSION_KEY, Constants.CURRENT_VERSION);
                try {
                    Result<Log> result = service.getLast(Constants.PACKAGE_NAME, options).execute().body();
                    if (result.getCode() != 0) {
                        lastVersion = false;
                        updateLog = result.getData();
                    } else {
                        lastVersion = true;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
}
